/*************************************************
* Title：TinyToolKit
* Author：Opportunity 
* Discribe：实现一些常用的扩展方法
* CreateTime：2020-04-26 14:30:17
* Version：1.0
* Modify Recoder：
*************************************************/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace TinyToolKit
{
    public static partial class TinyUtility
    {
        public static class SpaceConvert
        {
            public static Vector2 WorldToUIPoint(RectTransform canvas,Camera camera,Vector3 worldPos) 
            {
                var screenPos = Camera.main.WorldToScreenPoint(worldPos);
                return ScreenToUIPoint(canvas,camera,screenPos);  
            }

            public static Vector3 ScreenToUIPoint(RectTransform canvas,Camera camera,Vector3 screenPos) 
            {
                RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas,screenPos,camera,out var localPoint);
                return localPoint;
            }

            public static Vector3 UIToWorldPoint(RectTransform ui,Canvas uiCanvas,Camera mainCamera,float z)
            {   
                if(ui == null) return Vector3.zero;
                Vector2 res = uiCanvas.GetComponent<CanvasScaler>().referenceResolution;
                Vector2 pivotPos = new Vector2(0.5f * res.x ,0.5f * res.y); 
                Vector2 scale = new Vector2((pivotPos.x + ui.localPosition.x) / res.x, (pivotPos.y + ui.localPosition.y) / res.y);
                Vector2 screenPos = new Vector2(scale.x * Screen.width, scale.y * Screen.height); 
                return mainCamera.ScreenToWorldPoint(new Vector3(screenPos.x,screenPos.y,z)); 
            }
        }
    }
}

